package dosgi.core.tracker;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

import dbconnector.service.IServiceRegisterManager;
import dosgi.core.hook.HooksManager;

/**
 * Tracker which waits for database bundle to be set up and then registers hooks.
 * 
 * @author Jaroslaw Janik
 */
@SuppressWarnings({ "rawtypes" , "unchecked" })
public class DatabaseTrackerCustomizer implements ServiceTrackerCustomizer {

	private BundleContext context;
	private HooksManager hooksManager;
	
	public DatabaseTrackerCustomizer(HooksManager hooksManager, BundleContext context) {
		this.context = context;
		this.hooksManager = hooksManager;
	}
	
	/**
	 * Method invoked when database service is being registered in container. It also registers necessary hooks.
	 */
	@Override
	public Object addingService(ServiceReference reference) {
		IServiceRegisterManager databaseManager = context.getService(reference);
		
		hooksManager.setDatabase(databaseManager);
		
		return null;
	}

	@Override
	public void modifiedService(ServiceReference reference, Object service) {
		
	}

	/**
	 * Method invoked when database service is being unregistered from container. It also unregisters hooks.
	 */
	@Override
	public void removedService(ServiceReference reference, Object service) {
		hooksManager.setDatabase(null);
		
		context.ungetService(reference);
	}
}
